package com.inke.box.net.minasocket;

import org.apache.mina.core.session.IoSession;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/22.
 */

public class SessionSendUtils {

    private static SessionSendUtils sessionSendUtils;
    private static HashMap<String,IoSession> hashMap;
    private SessionSendUtils(){
    }

    public static SessionSendUtils getIns(){
        if (sessionSendUtils==null){
            sessionSendUtils = new SessionSendUtils();
            hashMap = new HashMap();
        }
        return sessionSendUtils;
    }

    public void setSession(IoSession session){
        hashMap.put(getKey(session),session);
    }

    public IoSession getSession(String key){
        if (hashMap.containsKey(key)){
            return  hashMap.get(key);
        }
        return null;
    }

    /**
     * 连接池获取回话对象发送消息
     * */
    public boolean sendMsg(String msg,IoSession session){
        if (hashMap.containsKey(getKey(session))){
            IoSession ioSession = hashMap.get(getKey(session));
            ioSession.write(msg+"\r");
            return true;
        }
        return false;
    }


    /**
     * 发送所有客户端数据
     * **/
    public boolean sendMsg(String msg){
        boolean isSend=false;
        Iterator<Map.Entry<String, IoSession>> iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, IoSession> next = iterator.next();
            next.getValue().write(msg+"\r");
            isSend = true;
        }
        return isSend;
    }

    /***
     * 客户端关闭连接 删除回话
     * */
    public void removeIosession(IoSession session){
        if (hashMap.containsKey(getKey(session)))
          hashMap.remove(getKey(session));
    }

    public String getKey(IoSession session){
        return ((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress();
    }

}
